import { _decorator, Component, game, JsonAsset, resources } from 'cc';
import { gameConfig } from '../data/gameConfig';
import { localData } from '../data/enums';
const { ccclass, property } = _decorator;

type LevelData = {
    levelIndex: number;
    grid: number[][];
    redPositions: number[][];
    playerPosition: number[];
}

@ccclass('LevelManager')
export class LevelManager extends Component {
    private static _instance: LevelManager;
    private _levels: LevelData[] = [];

    // 单例模式
    public static get Instance() {
        if (!this._instance) {
            this._instance = new LevelManager();
        }
        return this._instance;
    }

    // 加载JSON数据
    loadLevelData() {
        resources.loadDir(`data`, JsonAsset, (err, asset) => {
            if (err) {
                console.error('加载关卡数据失败:', err);
                return;
            }
            for (let i = 0; i < asset.length; i++) {
                for (let j = 0; j < asset[i].json.levels.length; j++) {
                    this._levels.push(asset[i].json.levels[j]);
                }
            }
            //this._levels = asset.json.levels;
            gameConfig.maxLevel = this._levels.length;
            console.log('关卡数据加载完成，已加载关卡数:', this._levels.length);
            console.log(this._levels);
            this.initLevelList();
        });
    }

    // 获取指定关卡数据
    getLevel(levelIndex: number): LevelData | null {
        //const data = this._levels.find(l => l.levelIndex === levelIndex);
        let data: LevelData = null;
        for (let i = 0; i < this._levels.length; i++) {
            if (this._levels[i].levelIndex === levelIndex) {
                data = this._levels[i];
                break;
            }
        }
        if (!data) {
            console.error(`关卡 ${levelIndex} 数据不存在`);
            return null;
        }
        return this.validateLevelData(data);
    }

    // 数据校验
    private validateLevelData(data: LevelData): LevelData {
        // 基础校验
        if (!data.grid || !data.redPositions || !data.playerPosition) {
            console.error(`关卡 ${data.levelIndex} 数据格式错误`);
            return null;
        }

        // 玩家位置校验
        if (!this.isValidPosition(data.grid, data.playerPosition)) {
            console.error(`关卡 ${data.levelIndex} 玩家初始位置无效`);
            return null;
        }

        return data;
    }

    // 验证坐标是否合法
    private isValidPosition(grid: number[][], [row, col]: number[]): boolean {
        return row >= 0 && row < grid.length &&
            col >= 0 && col < grid[row].length &&
            grid[row][col] === -1;
    }

    initLevelList() {
        const levelListJson = localStorage.getItem(localData.playerLevelData);
        // 检查 levelListJson 是否有效（非空且是字符串）
        let levelList = []; // 默认值
        if (levelListJson && typeof levelListJson === 'string') {
            try {
                levelList = JSON.parse(levelListJson);
            } catch (error) {
                console.error("解析 levelListJson 失败:", error);
                // 可选：保留默认值或设置兜底数据
            }
        }
        gameConfig.levelList = [];
        console.log(gameConfig.maxLevel);
        for (let i = 0; i < gameConfig.maxLevel; i++) {
            if (i <= 1) gameConfig.levelList.push(0);
            else gameConfig.levelList.push(-1);
        }
        if (levelList) {
            for (let i = 0; i < levelList.length; i++) {
                gameConfig.levelList[i] = levelList[i];
            }
        }
        console.log(gameConfig.levelList);
    }
}